package com.jsgt.greekfire.ui.main.snapup

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Typeface
import android.os.CountDownTimer
import android.text.TextUtils
import android.util.AttributeSet
import android.view.Gravity
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.base.BaseActivity
import com.fhx.core.utils.DateFormatUtil
import com.fhx.core.utils.ScreenUtil
import com.fhx.core.utils.ToastUtils
import com.jsgt.greekfire.IS_ACTIVATION
import com.jsgt.greekfire.LOGIN_STATUS
import com.jsgt.greekfire.R
import com.jsgt.greekfire.ZERO_COMPARE
import com.jsgt.greekfire.bean.SnapUpBean
import com.jsgt.greekfire.dialog.SecurityPwdDialog
import com.jsgt.greekfire.event.AssetsEvent
import com.jsgt.greekfire.event.TransferEvent
import com.jsgt.greekfire.factory.CoinViewModelFactory
import com.jsgt.greekfire.factory.UserViewModelFactory
import com.jsgt.greekfire.ui.main.snapup.adapter.SnapUpAdapter
import com.jsgt.greekfire.common.util.NetDataManager
import com.jsgt.greekfire.viewmodel.CoinViewModel
import com.jsgt.greekfire.viewmodel.UserViewModel
import kotlinx.android.synthetic.main.activity_snap_up.*
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.math.BigDecimal


/**
 * 抢购
 */
class SnapUpActivity : BaseActivity() {
    private val userViewModel: UserViewModel by lazy {
        ViewModelProvider(
            this,
            UserViewModelFactory()
        ).get(UserViewModel::class.java)
    }
    private val coinViewModel: CoinViewModel by lazy {
        ViewModelProvider(
            this,
            CoinViewModelFactory()
        ).get(CoinViewModel::class.java)
    }

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, SnapUpActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun getLayoutId(): Int = R.layout.activity_snap_up
    private var pwdDialog: SecurityPwdDialog? = null
    private var coinList: List<SnapUpBean>? = null
    private var countDownTimer: CountDownTimer? = null
    private var currentSnapUpBean: SnapUpBean? = null
    private var canSnapUpNum: Double? = null//可抢购数量
    private var usdt_balance = 0.0//可用usdt余额
    override fun main() {
        title = getString(R.string.snapped_up)
        val snapUpAdapter =
            SnapUpAdapter()
        recyclerView.adapter = snapUpAdapter

        if (LOGIN_STATUS) {
            NetDataManager.getUserAssets()
        }
        start_tv.setOnClickListener {
            if (IS_ACTIVATION == 1) {
                ToastUtils.show(this@SnapUpActivity, getString(R.string.account_no_activation))
            } else {
                val numberStr = buy_num_et.text.toString().trim()
                if (!TextUtils.isEmpty(numberStr)) {
                    val number = numberStr.toFloat()
                    if (number > canSnapUpNum!!) {
                        ToastUtils.show(this, "超过抢购数量上限")
                    } else {
                        if (number < currentSnapUpBean?.minQuota!! || number > currentSnapUpBean?.maxQuota!!) {
                            ToastUtils.show(
                                this,
                                "抢购数量有误,额度${currentSnapUpBean!!.minQuota}-${currentSnapUpBean!!.maxQuota}"
                            )
                        } else {

                            val buySum = currentSnapUpBean!!.conDecimal!! * number

                            if (usdt_balance < ZERO_COMPARE ||
                                BigDecimal(buySum.toString()).compareTo(BigDecimal(usdt_balance.toString())) == 1
                            ) {
                                ToastUtils.show(this, "余额不足")
                            } else {
                                initPwdDialog()
                                pwdDialog?.numberTv?.text = number.toString()
                                pwdDialog?.show()
                            }
                        }
                    }
                } else {
                    ToastUtils.show(this, "请输入抢购数量")
                }
            }
        }
        coinViewModel.residueAmount()
        coinViewModel.snapUpNumLiveData.observe(this, Observer {
            canSnapUpNum = it
            buy_num_et.hint = "剩余可抢购数量${it}"
        })
        coinViewModel.snappedUpCoinList()
        coinViewModel.snapUpListLiveData.observe(this, Observer {
            coinList = it.result
            currentSnapUpBean = it.current
            snapUpAdapter.currentGuid = it.current!!.guid
            scope_tv.text = "（抢购额度${it.current.minQuota}-${it.current.maxQuota} GFT）"
            progressbar.progress = it.surplusRatio!!.toInt()
            snap_up_remark_tv.text = currentSnapUpBean?.remark
            val snapUpBean = coinList!![0]
            if (coinList.isNullOrEmpty()) {
                snap_up_remark_tv.text = snapUpBean.remark
            }
            val millisInFuture = DateFormatUtil.dateDifference(it.current.startTime!!)
            if (DateFormatUtil.dateEquals(it.current.startTime!!)) {
                start_tv.text = getString(R.string.start)
                start_tv.setBackgroundColor(resources.getColor(R.color.white))
            } else {
                start_tv.text = getString(R.string.no_start)
                start_tv.isClickable = false
                start_tv.setTextColor(resources.getColor(R.color.gray_0D0F0F))
                start_tv.setBackgroundColor(resources.getColor(R.color.gray_B9B9B9))
                countDownTimer = object :
                    CountDownTimer(millisInFuture, 1000) {
                    override fun onFinish() {

                    }

                    override fun onTick(millisUntilFinished: Long) {
                        val day = millisUntilFinished / (1000 * 24 * 60 * 60) //单位天

                        val hour =
                            (millisUntilFinished - day * (1000 * 24 * 60 * 60)) / (1000 * 60 * 60)
                        //单位时
                        val minute =
                            (millisUntilFinished - day * (1000 * 24 * 60 * 60) - hour * (1000 * 60 * 60)) / (1000 * 60)
                        //单位分
                        val second =
                            (millisUntilFinished - day * (1000 * 24 * 60 * 60) - hour * (1000 * 60 * 60) - minute * (1000 * 60)) / 1000
                        //单位秒

                        if (day > 0) {
                            count_down_tv.text = "${day}天 $hour:$minute:$second"
                        } else {
                            count_down_tv.text = "$hour:$minute:$second"
                        }
                        if (millisUntilFinished <= 1000) {
                            start_tv.text = getString(R.string.start)
                            start_tv.setBackgroundColor(resources.getColor(R.color.white))
                            start_tv.isClickable = true
                        }
                    }
                }
                countDownTimer?.start()
            }
            snapUpAdapter.addData(it.result!!)
            //initIndicator()
        })

        coinViewModel.snapUpLiveData.observe(this, Observer {
            ToastUtils.show(this, "抢购成功")
            pwdDialog?.dismiss()
            EventBus.getDefault().post(TransferEvent(""))
            finish()
        })
        coinViewModel.snapUpErrorLiveData.observe(this, Observer {
            ToastUtils.show(this, it!!)
            showProgress(false)
        })
        coinViewModel.errorLiveData.observe(this, Observer {
            showProgress(false)
        })
        val checkPermission =
            ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
        if (checkPermission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.READ_PHONE_STATE),
                1
            )
        }
    }

    private fun initIndicator() {
        val commonNavigator = CommonNavigator(this)
        commonNavigator.isAdjustMode = false
        commonNavigator.adapter = object : CommonNavigatorAdapter() {
            override fun getCount(): Int {
                return coinList!!.size
            }

            override fun getTitleView(context: Context, index: Int): IPagerTitleView {
                val colorTransitionPagerTitleView = ColorTransitionPagerTitleView(context)
                colorTransitionPagerTitleView.normalColor =
                    ContextCompat.getColor(context, R.color.gray_4C5E6A)
                colorTransitionPagerTitleView.selectedColor =
                    ContextCompat.getColor(context, R.color.white)
                val snapUpBean = coinList!![index]
                colorTransitionPagerTitleView.text =
                    "${snapUpBean.ratio}%\n${snapUpBean.conDecimal}U"
                colorTransitionPagerTitleView.setLines(2)
                colorTransitionPagerTitleView.maxLines = 2
                colorTransitionPagerTitleView.textSize = 14f
                colorTransitionPagerTitleView.setOnClickListener {
                    //do something
                }
                val view =
                    NavigationView(
                        this@SnapUpActivity
                    )
                view.setText(coinList!![index].ratio!!, coinList!![index].conDecimal!!.toString())
                return NavigationView(
                    this@SnapUpActivity
                )
            }

            override fun getIndicator(context: Context): IPagerIndicator {
                val linePagerIndicator = LinePagerIndicator(context)
                linePagerIndicator.mode = LinePagerIndicator.MODE_EXACTLY
                linePagerIndicator.setColors(ContextCompat.getColor(context, R.color.white))
                linePagerIndicator.lineWidth = ScreenUtil.dip2px(context, 45f)
                linePagerIndicator.lineHeight = ScreenUtil.dip2px(context, 1f)
                return linePagerIndicator
            }
        }
        indicator.navigator = commonNavigator
    }

    private fun initPwdDialog() {
        pwdDialog = SecurityPwdDialog(mContext!!, R.style.dialog)
        pwdDialog?.inputCallback = object : SecurityPwdDialog.InputCallback {
            override fun callBack(result: String) {
                coinViewModel.snappedUpCoin(
                    coinList!![0].guid!!,
                    buy_num_et.text.toString(),
                    result
                )
                pwdDialog?.dismiss()
                showProgress(true)
            }
        }
    }

    class NavigationView(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
        LinearLayout(context, attrs, defStyleAttr), IPagerTitleView {
        constructor(context: Context) : this(context, null)
        constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

        private var tv1: TextView? = null
        private var tv2: TextView? = null

        init {
            orientation = VERTICAL
            gravity = Gravity.CENTER_VERTICAL
            tv1 = TextView(context)
            tv1?.paint?.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
            tv1?.setTextColor(context.resources.getColor(R.color.white))
            tv2 = TextView(context)
            tv2?.setPadding(0, ScreenUtil.dip2px(context, 10f).toInt(), 0, 0)
            tv2?.paint?.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
            tv2?.setTextColor(context.resources.getColor(R.color.white))
            addView(tv1)
            addView(tv2)
        }

        fun setText(str1: String, str2: String) {
            tv1?.text = "$str1%"
            tv2?.text = str2 + "U"
        }

        override fun onDeselected(index: Int, totalCount: Int) {
        }

        override fun onSelected(index: Int, totalCount: Int) {
        }

        override fun onLeave(
            index: Int,
            totalCount: Int,
            leavePercent: Float,
            leftToRight: Boolean
        ) {
        }

        override fun onEnter(
            index: Int,
            totalCount: Int,
            enterPercent: Float,
            leftToRight: Boolean
        ) {
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        countDownTimer?.cancel()
        countDownTimer = null
        pwdDialog?.dismiss()
        pwdDialog = null
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onAssetsEvent(e: AssetsEvent) {
        for (i in NetDataManager.assetsList) {
            if (TextUtils.equals("USDT", i.assetName)) {
                usdt_balance = i.assetBalance!!
                break
            }
        }
        balance_tv.text = "余额 $usdt_balance USDT"
    }
}